import React, { useState, useEffect, useRef } from 'react';
import {
  Button,
  Modal,
  Form,
  Input,
  Select,
  message,
  InputNumber,
  Popconfirm,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import type { ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import TableTitle from '@/components/TableTitle';
import { deliverRulerColumnsData } from './data';
import { getDictType } from '@/services/services';
import { getLocalStorageInfo } from '@/utils/localStorageInfo';
import type {
  DeliverRulerColumnsItem,
  DictItemType,
  ThemeItemType,
  AirdropParamsType,
  ThemeFragmentsItemType,
} from './data';
import {
  getDeliverRulerList,
  addDeliverRulers,
  getThemeNftList,
  airdrop,
  deleteDeliverRulers,
  DeliverRulerInfo,
  getFragmentsByThemeNo,
} from './service';

const { Option } = Select;
const { TextArea } = Input;

const DeliverRuler = () => {
  // 控制添加模态框
  const [isAddModalVisible, setIsAddModalVisible] = useState<boolean>(false);
  // 空投范围表
  const [deliverScope, setDeliverScope] = useState<DictItemType[] | null>();
  // 空投物类型表
  const [deliverTypeList, setDeliverTypeList] = useState<
    DictItemType[] | null
  >();
  // 空投物类型编号
  const [deliverType, setDeliverType] = useState<string | null>();
  // 空投主题表
  const [themeList, setThemeList] = useState<ThemeItemType[]>();
  // 空投碎片表
  const [fragmentsList, setFragmentsList] = useState<ThemeFragmentsItemType[]>(
    [],
  );

  /**
   * 执行投放
   * @param record 执行的规则对象
   */
  const delivering = async (record: DeliverRulerColumnsItem) => {
    const { serialNo: airdropRuleNo, type, amount, typeNo } = record;
    let params: AirdropParamsType = { airdropRuleNo, type, amount };
    if (type !== 1) {
      params = { ...params, typeNo };
    }
    let res = await airdrop(params);
    console.log(res);
    if (res.code !== '000000') message.error('投放失败');
    message.success('投放成功！');
    deliverRulerActionRef.current?.reload();
  };

  /**
   * 执行删除
   * @param record 删除的规则对象
   */
  const delRuler = async (record: DeliverRulerColumnsItem) => {
    const { serialNo } = record;
    let res = await deleteDeliverRulers({ serialNo });
    console.log(res);
    if (res.code !== '000000') message.error('删除失败');
    message.success('删除成功！');
    deliverRulerActionRef.current?.reload();
  };

  /**
   * 点击查看
   * @param record 查看的规则对象
   */
  const view = async (record: DeliverRulerColumnsItem) => {
    const { serialNo } = record;
    let res = await DeliverRulerInfo({ serialNo });
    console.log(res);
  };

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      {record.status == '1' ? (
        <>
          <li>
            <Popconfirm
              title="确定开始投放？"
              okText="是"
              cancelText="否"
              onConfirm={() => {
                delivering(record);
              }}
            >
              <a>投放</a>
            </Popconfirm>
            <em className="ant-list-item-action-split"></em>
          </li>
          <li>
            <Popconfirm
              title="确定删除此条规则？"
              okText="是"
              cancelText="否"
              onConfirm={() => {
                delRuler(record);
              }}
            >
              <a>删除</a>
            </Popconfirm>
            <em className="ant-list-item-action-split"></em>
          </li>
        </>
      ) : null}
      <li>
        <a onClick={() => view(record)}>查看</a>
      </li>
    </ul>
  );

  // 绑定表格渲染样式
  deliverRulerColumnsData.forEach((item) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : null;
  });

  /**
   * 点击添加规则按钮调用
   */
  const addDeliverRuler = async () => {
    console.log('addDeliverRuler');
    setIsAddModalVisible(true);
    // 获取空投范围字典
    let res = await getDictType({
      dictType: 'deliver-scope',
      pageSize: 100,
      current: 1,
    });
    console.log(res);
    if (res.code !== '000000')
      message.info('获取空投范围选项失败，请检查字典库！');
    setDeliverScope(res.data);
    // 获取空投物类型字典
    let data = await getDictType({
      dictType: 'deliver-type',
      pageSize: 100,
      current: 1,
    });
    console.log(data);
    if (data.code !== '000000')
      message.info('获取空投物类型选项失败，请检查字典库！');
    setDeliverTypeList(data.data);
  };

  /**
   * 空投物类型改变时调用
   */
  const onDeliverTypeChange = async (e: string) => {
    console.log(e);
    setDeliverType(e);
    if (e == '2' || e == '3') {
      let res = await getThemeNftList({
        current: 1,
        pageSize: 100,
      });
      console.log(res);
      setThemeList(res.data);
    }
  };

  /**
   * 空投碎片主题改变时调用
   */
  const onThemeChange = async (e: string) => {
    console.log(e);
    let res = await getFragmentsByThemeNo({
      current: 1,
      pageSize: 20,
      serialNo: e,
    });
    console.log(res);
    setFragmentsList(res.data);
  };

  /**
   * 添加模态框确定按钮调用
   */
  const handleAddOk = async () => {
    console.log('handleAddOk');
    // 表单验证
    await addFormRef.validateFields();
    let response = addFormRef.getFieldsValue();
    console.log(response);
    let type = Number(response.type);
    let airdropRange = Number(response.airdropRange);
    let customerNo = getLocalStorageInfo('customerInfo').customerNo;
    let res = await addDeliverRulers({
      ...response,
      customerNo,
      type,
      airdropRange,
    });
    console.log(res);
    deliverRulerActionRef.current?.reload();
    setIsAddModalVisible(false);
  };

  /**
   * 添加模态框取消按钮调用
   */
  const handleAddCancel = () => {
    addFormRef.resetFields();
    setIsAddModalVisible(false);
    console.log('handleAddCancel');
  };

  // 绑定表格和搜索表单，方便自定义操作
  const deliverRulerActionRef = useRef<ActionType>();
  const searchFormRef = useRef<ProFormInstance>();
  // 绑定添加规则表单
  const [addFormRef] = Form.useForm();
  return (
    <>
      <ProTable<DeliverRulerColumnsItem>
        // 表格标题
        headerTitle={<TableTitle title="投放规则" />}
        //配置工具栏按钮
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={addDeliverRuler}
          >
            添加规则
          </Button>,
        ]}
        // 绑定表格
        actionRef={deliverRulerActionRef}
        // 绑定搜索表单
        formRef={searchFormRef}
        // 绑定单元格格式
        columns={deliverRulerColumnsData}
        // 最小宽度
        scroll={{ x: 900 }}
        // 单元格边框显示
        bordered
        // 请求数据
        request={async (params) => {
          console.log(params);
          let res = await getDeliverRulerList({ ...params });
          console.log(res);
          let result = {
            data: [],
            total: 0,
          };
          if (res.code === '000000') {
            result = {
              data: res.data,
              total: res.pagination.totalSize,
            };
          }
          return result;
        }}
        // 本地储存表格列的显示参数
        columnsState={{
          persistenceKey: 'DeliverRulerList',
          persistenceType: 'localStorage',
        }}
        // 每行表格的key
        rowKey="serialNo"
        // 搜索表单布局配置
        search={{
          labelWidth: 'auto',
        }}
        // 分页相关配置
        pagination={{
          // 初始页面数据条数
          pageSize: 10,
        }}
        dateFormatter="string"
      />
      {/* 添加规则模态框 */}
      <Modal
        title="添加投放规则"
        centered
        visible={isAddModalVisible}
        onOk={handleAddOk}
        onCancel={handleAddCancel}
        width={700}
      >
        <Form
          name="basic"
          form={addFormRef}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 12 }}
          autoComplete="off"
        >
          <Form.Item
            label="规则名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入规则名称', // 验证失败提示
              },
            ]}
          >
            <Input maxLength={20} />
          </Form.Item>
          <Form.Item
            label="规则编码"
            name="code"
            rules={[
              {
                required: true,
                message: '请输入规则编号', // 验证失败提示
              },
            ]}
          >
            <Input maxLength={20} />
          </Form.Item>
          <Form.Item
            label="空投范围"
            name="airdropRange"
            rules={[
              {
                required: true,
                message: '请选择空投范围', // 验证失败提示
              },
            ]}
          >
            <Select>
              {deliverScope?.map((item) => (
                <Option key={item.itemValue} value={item.itemValue}>
                  {item.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="投放物"
            name="type"
            rules={[
              {
                required: true,
                message: '请选择投放物', // 验证失败提示
              },
            ]}
          >
            <Select onChange={onDeliverTypeChange}>
              {deliverTypeList?.map((item) => (
                <Option key={item.itemValue} value={item.itemValue}>
                  {item.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          {deliverType == '2' ? (
            <Form.Item
              label="请选择主题"
              name="typeNo"
              rules={[
                {
                  required: true,
                  message: '请选择空投主题', // 验证失败提示
                },
              ]}
            >
              <Select>
                {themeList
                  ?.filter((item) => item.fragmentsFlag == '0')
                  .map((item) => (
                    <Option key={item.serialNo} value={item.serialNo}>
                      {item.themeName}
                      {item.sex == 0 ? '(男)' : null}
                      {item.sex == 1 ? '(女)' : null}
                    </Option>
                  ))}
              </Select>
            </Form.Item>
          ) : null}
          {deliverType == '3' ? (
            <>
              <Form.Item
                label="请选择主题"
                name="themeTypeNo"
                rules={[
                  {
                    required: true,
                    message: '请选择空投主题', // 验证失败提示
                  },
                ]}
              >
                <Select onChange={onThemeChange}>
                  {themeList
                    ?.filter((item) => item.fragmentsFlag == '1')
                    .map((item) => (
                      <Option key={item.serialNo} value={item.serialNo}>
                        {item.themeName}
                        {item.sex == 0 ? '(男)' : null}
                        {item.sex == 1 ? '(女)' : null}
                      </Option>
                    ))}
                </Select>
              </Form.Item>
              <Form.Item
                label="请选择碎片"
                name="typeNo"
                rules={[
                  {
                    required: true,
                    message: '请选择空投碎片', // 验证失败提示
                  },
                ]}
              >
                <Select>
                  {fragmentsList?.map((item) => (
                    <Option key={item.serialNo} value={item.serialNo}>
                      {item.fragmentsSerialNo}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </>
          ) : null}
          <Form.Item
            label="投放数量"
            name="amount"
            rules={[
              {
                required: true,
                message: '请输入积分数量', // 验证失败提示
              },
            ]}
          >
            <InputNumber min={1} />
          </Form.Item>
          {/* {
            deliverType == '1' ?
              <Form.Item
                label="积分种类"
                name="ccy"
                rules={[
                  {
                    required: true,
                    message: '请输入积分种类', // 验证失败提示
                  },
                ]}
              >
                <Select>
                  {themeList?.map((item) => (
                    <Option key={item.serialNo} value={item.serialNo}>
                      {item.themeName}
                      {item.sex == 0 ? '(男)' : null}
                      {item.sex == 1 ? '(女)' : null}
                    </Option>
                  ))}
                </Select>
              </Form.Item> : null
          } */}
          <Form.Item
            label="规则描述"
            name="description"
            rules={[
              {
                required: true,
                message: '请选择空投主题', // 验证失败提示
              },
            ]}
          >
            <TextArea />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default DeliverRuler;
